import React, { ReactNode } from 'react';
import { Alert, Modal } from 'antd';
import { connect } from 'dva';
import { mapStateToProps } from '@/pages/riskControl/utils';
import RiskForm from './form/form';
import RiskInquiryTable from './table/table';
import { LockModal, ModifyLevelModal } from '@/pages/riskControl/externalInquiry/inquiry/modal';
import { ObjectType } from '../../utils';
import styles from './index.less';

interface MyStateType {
  lockModalVisible: boolean;
  modifyLevelModalVisible: boolean;
  batchOperation: boolean;
  lockedOneUserData: ObjectType;
}

class RiskInquiry extends React.PureComponent<ObjectType, MyStateType> {
  public state = {
    lockModalVisible: false, // 显示锁定modal
    modifyLevelModalVisible: false, // 显示修改层级modal
    // 点击行修改用户的锁定状态时获取的该行数据
    lockedOneUserData: {
      username: undefined,
      userId: undefined,
    },
    // 批量操作标示
    batchOperation: false,
  };

  toSetState = (attr: string, b: boolean, callback?: () => void) => {
    // @ts-ignore
    this.setState({ [attr]: b }, callback);
  };

  destroyAll = () => {
    Modal.destroyAll();
  };

  // 批量操作变化
  toBatchOperation = (b: boolean) => {
    this.toSetState('batchOperation', b);
  };

  // ------------------锁定modal--------------------------
  /**
   * 显示锁定modal
   * @param {object} record 打开锁定modal行的数据
   * @param batchOperation 批量操作
   */
  showLockModal = (record: ObjectType, batchOperation: boolean = false) => {
    this.setState({
      lockModalVisible: true,
      lockedOneUserData: record,
      batchOperation,
    });
  };

  /*
   * 点击锁定modal确认按钮
   */
  handleLockOk = ({ remark, optType }: { remark: string; optType: number }) => {
    const { lockedOneUserData, batchOperation } = this.state;
    const {
      tableData: { selectedUserList },
    } = this.props.risk;
    const ids = selectedUserList.map((val: ObjectType) => val.userId);
    const userIds = batchOperation ? ids.join(',') : lockedOneUserData.userId;
    this.props.dispatch({
      type: 'risk/setUserLockStatusEffect',
      payload: {
        userIds,
        remark,
        optType,
      },
    });
    this.clearSelectTableData();
    this.toSetState('lockModalVisible', false, this.destroyAll);
  };

  /*
   * 点击锁定modal取消或者关闭按钮
   */
  handleLockCancel = () => {
    this.toSetState('lockModalVisible', false, this.destroyAll);
  };

  // ------------------修改层级的modal--------------------------
  /*
   * 显示修改层级modal
   */
  showModifyLevelModal = (record: ObjectType, batchOperation: boolean = false) => {
    const { userLevelList } = this.props.risk.modifyUserLevelModalData;
    if (!userLevelList.length) {
      this.props.dispatch({
        type: 'risk/getUserLevelListEffect',
        payload: {
          levelType: 0,
        },
      });
    }
    this.setState({
      modifyLevelModalVisible: true,
      lockedOneUserData: record,
      batchOperation,
    });
  };

  /*
   * 点击'修改层级'modal确认按钮
   */
  handleModifyLevelOk = () => {
    const { lockedOneUserData, batchOperation } = this.state;
    const {
      tableData: { selectedUserList },
      modifyUserLevelModalData: { selectUserLevel },
    } = this.props.risk;
    const username = batchOperation
      ? selectedUserList.map((val: ObjectType) => val.username).join(',')
      : lockedOneUserData.username;
    if (selectUserLevel.levelId) {
      // 修改层级
      this.props.dispatch({
        type: 'risk/modifyUserLevelEffect',
        payload: {
          username,
          levelId: selectUserLevel.levelId,
        },
      });
      // 修改层级以后，清空选中层级的保留数据 确保下次打开模态框时候确定按钮的可用状态正常
      this.handleModifyLevelCancel();
      this.clearSelectTableData();
    }
    this.toSetState('modifyLevelModalVisible', false, this.destroyAll);
  };

  // 清空表格选中的数据
  clearSelectTableData = () => {
    this.props.dispatch({
      type: 'risk/saveSelectedUserList',
      payload: [],
    });
  };

  /*
   * 点击修改层级modal取消或者关闭按钮 清空选中层级的保留数据和销毁modal
   */
  handleModifyLevelCancel = () => {
    // 修改层级以后，清空选中层级的保留数据
    this.props.dispatch({
      type: 'risk/setSelectUserLevel',
      payload: {},
    });
    this.toSetState('modifyLevelModalVisible', false, this.destroyAll);
  };

  clearSelectedTableColumns = () => {
    this.props.dispatch({
      type: 'risk/clearSelectedTableColumns',
      payload: {},
    });
  };

  clearBarMessage = (unSelectedUserTotal: number) => (
    <div>
      <span>
        已经选择 <em className={styles.blue}>{unSelectedUserTotal}</em> 项
      </span>
      <span className={styles.clearBtn} onClick={this.clearSelectedTableColumns}>
        清空
      </span>
    </div>
  );

  public render(): ReactNode {
    const {
      lockModalVisible,
      modifyLevelModalVisible,
      lockedOneUserData,
      batchOperation,
    } = this.state;
    const {
      tableData: { selectedUserList, userListColumns },
    } = this.props.risk;
    return (
      <div className={styles.riskExternalInquiryCon}>
        <RiskForm
          toBatchOperation={this.toBatchOperation}
          showLockModal={this.showLockModal}
          showModifyLevelModal={this.showModifyLevelModal}
        />
        <Alert
          message={this.clearBarMessage(selectedUserList.length)}
          type="info"
          showIcon
          className={styles['alert-banner']}
        />
        <RiskInquiryTable
          showLockModal={this.showLockModal}
          showModifyLevelModal={this.showModifyLevelModal}
        />
        {lockModalVisible && (
          <LockModal
            title="申请：锁定"
            visible={lockModalVisible}
            handleOk={this.handleLockOk}
            handleCancel={this.handleLockCancel}
            isGroupOption={batchOperation} // 批量操作
            rowData={[lockedOneUserData]} // 单行修改数据
            rowsData={selectedUserList} // 批量操作选中修改数据
            userListColumns={userListColumns}
          />
        )}
        {modifyLevelModalVisible && (
          <ModifyLevelModal
            title="修改用户层级"
            visible={modifyLevelModalVisible}
            handleOk={this.handleModifyLevelOk}
            handleCancel={this.handleModifyLevelCancel}
            rowData={[lockedOneUserData]} // 单行修改数据
            rowsData={selectedUserList} // 批量操作选中修改数据
            isGroupOption={batchOperation} // 批量操作
          />
        )}
      </div>
    );
  }
}

export default connect(mapStateToProps)(RiskInquiry);
